package cnet

import (
	"bytes"
	"encoding/binary"
	"errors"
	"github.com/cmajor/cherry/iface"
	"github.com/cmajor/cherry/utils"
	"io"
)

type BaseParser struct{

}

func (p *BaseParser)UnMarshal(b []byte)(interface{},error){
	return b,nil
}

func (p *BaseParser)Marshal(param interface{})([]byte,error){
	msg := param.(*iface.InternalMsg)
	dataBuff := bytes.NewBuffer([]byte{})

	err := binary.Write(dataBuff, binary.LittleEndian, uint32(len(msg.Content)))
	if err != nil {
		return nil, err
	}

	err = binary.Write(dataBuff, binary.LittleEndian,msg.MsgID)
	if err != nil {
		return nil, err
	}

	err = binary.Write(dataBuff, binary.LittleEndian, msg.Content)
	if err != nil {
		return nil, err
	}

	return dataBuff.Bytes(), nil
}

type ConnReader struct{
}

func(r *ConnReader)Read(reader io.Reader,buff iface.IBuffer)(interface{},error){
	head := buff.ApplyBufferSize(iface.MSG_HEAD_LEN)
	if _,err := reader.Read(head);err != nil{
		return nil,err
	}
	msglen := binary.LittleEndian.Uint32(head)

	if int(msglen) > utils.MaxPackageSize(){
		return nil,errors.New("over MaxPackageSize")
	}

	mid := buff.ApplyBufferSize(iface.MSG_HEAD_ID)
	if _,err := reader.Read(mid);err != nil{
		return nil,err
	}
	msgID := binary.LittleEndian.Uint32(mid)

	cb := buff.ApplyBufferSize(int(msglen))
	if _,err := reader.Read(cb);err != nil{
		return nil,err
	}

	imsg := &iface.InternalMsg{}
	imsg.SysID = iface.NOTIFY_TCP_READ
	imsg.Content = cb
	imsg.MsgID = msgID
	return imsg,nil


}